package com.hongdee.scm;

import com.hongdee.base.entity.ResultEntity;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.stock.dao.ITScmStockDao;
import com.hongdee.scm.stock.service.ITScmStockService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

/**
 * Created by Mr. Xu on 2017/4/25.
 */
public class Common {
    @Autowired
    private ITScmStockDao itScmStockDao;
    public Boolean appendWhereIfNeed(StringBuffer sql,Boolean hasWhere){

        if(hasWhere == false){

            sql.append(" where ");

        }else{

            sql.append(" and ");

        }
        return true;

    }
    /**
     * 公司下仓库下的车辆
     */
    public List carOfCompany (String uid) throws Exception{
       return this.itScmStockDao.list("SELECT * FROM T_SCM_STOCK where warehouse_id in (select id from T_SCM_WAREHOUSE where company_id = ? )" , TokenUtil.getCompanyId(uid));
    }

    public static String uploadPath(HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath(".");
        path =   path + File.separator + "upload";
        return path;
    }
    public static String copyExcelToNewPath(HttpServletRequest request,String fileName) throws IOException {
        int bytesum = 0;
        int byteread = 0;
        String path = uploadPath(request);
        String fileId = StringUtil.UUID();

        String oldPath = path + File.separator + fileName + ".xlsx";
        String newPath = path + File.separator + fileId + ".xlsx";

        InputStream inStream = new FileInputStream(oldPath); //读入原文件
        FileOutputStream fs = new FileOutputStream(newPath);
        byte[] buffer = new byte[1444];
        while ((byteread = inStream.read(buffer)) != -1) {
            bytesum += byteread; //字节数 文件大小
            fs.write(buffer, 0, byteread);
        }
        inStream.close();
        fs.close();

        return fileId;
    }

    public static ResultEntity expExcel(HttpServletRequest request, XSSFWorkbook wb) throws IOException {
        String path = uploadPath(request);
        String fileId = StringUtil.UUID();
        File filepack = new File(path);
        if(!filepack.exists()){
            filepack.mkdir();
        }
        String filePath =   path + File.separator + fileId + ".xlsx";
        File file = new File(filePath);
        file.createNewFile();
        FileOutputStream fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
        ResultEntity res = new ResultEntity();
        res.setSuccess(true);
        res.setData(fileId);
        res.setMsg("文件生成成功！");
        return res;
    }
}
